package com.test.platform.network

import android.util.Log
import okhttp3.Dispatcher
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import okhttp3.logging.HttpLoggingInterceptor.Level // 针对 Level 的引用
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import okhttp3.Interceptor  // 添加这个导入

object RetrofitClient {
    private const val BASE_URL = "http://192.168.1.103:8080/"

    private val retrofit: Retrofit by lazy {
        // 创建详细的日志拦截器
        val loggingInterceptor = HttpLoggingInterceptor { message ->
            Log.d("NetworkLog", message)
        }.apply {
            level = HttpLoggingInterceptor.Level.BODY
        }
        
        // 添加网络状态拦截器
        val networkInterceptor = Interceptor { chain ->
            try {
                val request = chain.request()
                Log.d("NetworkLog", "Sending request: ${request.url}")
                
                val response = chain.proceed(request)
                Log.d("NetworkLog", "Received response: ${response.code}")
                
                response
            } catch (e: Exception) {
                Log.e("NetworkLog", "Network error: ${e.message}", e)
                throw e
            }
        }

        val client = OkHttpClient.Builder()
            .addInterceptor(loggingInterceptor)
            .addInterceptor(networkInterceptor)
            .connectTimeout(30, TimeUnit.SECONDS)  // 增加超时时间
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .dispatcher(Dispatcher().apply {
                maxRequestsPerHost = 20
                maxRequests = 20
            })
            .build()

        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    val apiService: ApiService by lazy {
        retrofit.create(ApiService::class.java)
    }
}